package cn.myjerry.net.tcp.chat.demo03;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * 创建服务器
 * @author Jerry
 *
 */
public class Server {
	private List<MyChannel> all = new ArrayList<>();
	
	public static void main(String[] args) throws IOException {
		new Server().start();
		
	}
	
	public void start() throws IOException {
		ServerSocket server = new ServerSocket(9999);
		
		while(true) {
			Socket socket = server.accept();
			MyChannel channel = new MyChannel(socket);
			all.add(channel);
			new Thread(channel).start();
		}
	}
	
	private class MyChannel implements Runnable {
		private DataInputStream dis;
		private DataOutputStream dos;
		private Boolean isRunning = true;
		
		public MyChannel(Socket client){
			try {
				dis = new DataInputStream(client.getInputStream());
				dos = new DataOutputStream(client.getOutputStream());
			} catch (IOException e) {
				//e.printStackTrace();
				isRunning = false;
				CloseUtil.closeAll(dis, dos);
				all.remove(this);
			}
		}
		
		private String receive() {
			String msg = "";
			try {
				msg = dis.readUTF();
			} catch (IOException e) {
				//e.printStackTrace();
				isRunning = false;
				CloseUtil.closeAll(dis);
				all.remove(this);
			}
			
			return msg;
		}
		
		private void send(String msg) {
			try {
				dos.writeUTF("返回：-->" + msg);
				dos.flush();
			} catch (IOException e) {
				//e.printStackTrace();
				isRunning = false;
				CloseUtil.closeAll(dis);
				all.remove(this);
			}
		}
		
		private void sendOthers() {
			String msg = this.receive();
			for(MyChannel other:all) {
				if(other == this) {
					continue;
				}
				other.send(msg);
			}
		}
		
		@Override
		public void run() {
			while(isRunning) {
				//send(receive());
				sendOthers();
			}
		}
		
	}
}
